import { Col, Modal, message, Row, TreeSelect } from 'antd';
import { useEffect, useState } from 'react';
import { getProductCategoryList, moveProduct } from '@/services/product';

type Props = {
  selectedRowKeys: number[];
  onClose?: (reflash?: boolean) => void;
};
const App = ({ onClose, selectedRowKeys }: Props) => {
  const [productCategoryId, setProductCategoryId] = useState<
    number | undefined
  >();
  const [treeData, setTreeData] = useState<any[]>([]);

  const getData = async () => {
    const { data } = await getProductCategoryList({});

    const resetTree = (data: any, parentId?: undefined) => {
      return data?.map((item: any) => ({
        title: item.categoryName,
        value: item.id,
        parentId,
        children: resetTree(item.subList || [], item.id),
      }));
    };

    const formattedTree = resetTree(data);
    setTreeData(formattedTree);
  };
  const moveProducts = async (ids: any, productCategoryId: any) => {
    const { success } = await moveProduct({ ids, productCategoryId });
    if (success) {
      message.success('移动成功');
      onClose?.(true);
    }
  };
  useEffect(() => {
    getData();
  }, []);
  return (
    <Modal
      width={400}
      title="信息提示"
      open
      okButtonProps={{
        disabled: productCategoryId === undefined,
      }}
      onCancel={() => onClose?.()}
      onOk={() => {
        moveProducts(selectedRowKeys, productCategoryId);
      }}
    >
      <Row gutter={[10, 10]}>
        <Col span={24}>请选择所属分类</Col>
        <Col span={24}>
          <TreeSelect
            treeData={treeData}
            placeholder="请选择产品分类"
            onChange={(ev) => {
              setProductCategoryId(ev as number);
            }}
            style={{
              width: '100%',
            }}
          />
        </Col>
      </Row>
    </Modal>
  );
};
export default App;
